package com.iftreer.demo.sso;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.itfreer.power.entity.user.VUserInfoEntity;

@Component
public class CurrentUserDemo {

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	private final static String user_attributes = "user_attributes";
	private final static String user_id = "user_id";
	private final static String s_user = "s_user";

	/**
	 * 1.只集成单点登录下，登录成功后，获取当前登录用户ID
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String getUserIdForSSO(HttpServletRequest request) {
		final HttpSession httpSession = request.getSession(false);
		// 获取登录用户id
		final Map<String, Object> userAttribute = httpSession != null
				? (Map<String, Object>) httpSession.getAttribute(user_attributes)
				: null;
		if (userAttribute == null) {
			// 未登录系统！
			return null;
		}

		String userId = null;
		if (userAttribute.containsKey(user_id)) {
			userId = userAttribute.get(user_id).toString();
		}
		if (userId == null) {
			String ouserid = user_id.toUpperCase();
			if (userAttribute.containsKey(ouserid)) {
				userId = userAttribute.get(ouserid).toString();
			}
		}
		return userId;
	}

	/**
	 * 2.平台体系下系统(dubbo集成，或独立部署)，获取当前登录用户信息
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public VUserInfoEntity getCurrentUser(HttpServletRequest request) throws IOException {
		if (request == null) {
			logger.debug("获取当前用户失败，request为null。");
			return null;
		}
		final HttpSession httpSession = request.getSession(false);
		if (httpSession == null) {
			logger.debug("获取当前用户失败，httpSession为null。");
		}
		VUserInfoEntity userEntity = httpSession != null ? (VUserInfoEntity) httpSession.getAttribute(s_user) : null;
		if (userEntity == null) {
			logger.debug("获取当前用户失败，userEntity为null。");
		} else {
			logger.debug("获取当前用户成功，用户名为：" + userEntity.getUserName());
		}
		return userEntity;
	}
}